#!/usr/bin/python3

import logging
from fastapi import APIRouter, status
from fastapi.responses import JSONResponse
from utils.neo4j_provider import asyncDriver
from settings import settings

router = APIRouter()


# 定义一个根路由
@router.get("/add")
def add_node():
    # TODO 往 neo4j 里创建新的节点
    data = {
        'code': 0,
        'message': '',
        'data': 'add success'
    }
    return JSONResponse(content=data, status_code=status.HTTP_200_OK)


@router.route("/search")
async def get_search(q: str = None):
    if q is None:
        return []
    cql = ("""
                 MATCH (p:Person) WHERE p.name CONTAINS $name RETURN p
             """)
    records, _, _ = await asyncDriver.execute_query(
        cql,
        name=q.query_params['name'],  # 将参数 q 传给cql 里的 $name 变量
        database_=settings.NEO4J_DATABASE,
        routing_="r",
    )
    for record in records:
        # 打印出 record 属性
        logging.info("%s, %s", record["p"]["name"], record["p"]["generation"])
    # 转成 json
    data = [serialize_person(record["p"]) for record in records]
    return JSONResponse(content=data, status_code=status.HTTP_200_OK)


def serialize_person(person):
    return {
        "id": person["id"],
        "name": person["name"],
        "generation": person["generation"],
        "votes": person.get("votes", 0)
    }
